<script setup lang="ts">
  import routeComponentName from '@/config/route-component-name'
  import { nextTick, onMounted, ref } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { useFindTemplateById } from '../hooks/useTemplateList'
  import { useCustomProcessForm, useFindCustomPorcess } from '../hooks/useProcess'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import { CustomProcessNode } from '../hooks/types'
  import nodeList from './node-list.vue'
  import setting from './setting.vue'
  import _ from 'lodash'
  import { v4 as uuidv4 } from 'uuid'
  import { HMessageBox } from '@/components/common/message'

  defineOptions({
    name: routeComponentName.order.customProcess,
  })

  const { template, findLoading, findTemplate } = useFindTemplateById()
  const { form, formSaveLoading, formSave, resetForm } = useCustomProcessForm()
  const { processList, findProcessListLoading, findPorcessList } = useFindCustomPorcess()

  const router = useRouter()
  const tagsViewStore = useTagsViewStore()
  const route = useRoute()
  const activeNode = ref<null | CustomProcessNode>(null)
  const settingInsatnce = ref<InstanceType<typeof setting> | null>(null)

  const onCancelClick = () => {
    resetForm()
    tagsViewStore.delView(route.path)
    router.push('/order/custom/templates')
  }

  const handleNodeClick = (node: CustomProcessNode) => {
    activeNode.value = _.cloneDeep(node)
    nextTick(() => {
      if (settingInsatnce.value) {
        settingInsatnce.value.getNodeCommanderList()
      }
    })
  }

  const handleSettingUpdate = (node: CustomProcessNode) => {
    const index = form.value.nodes.findIndex((item) => item.id === node.id)
    if (index >= 0) {
      form.value.nodes[index] = _.cloneDeep(node)
    }
  }

  const onSaveClick = async () => {
    if (form.value.nodes.some((node) => !node.name)) {
      HMessageBox.error('节点名称不能为空')
      return
    }
    await formSave()
    onCancelClick()
  }

  const handleAddNodeClick = (nodeIndex: number) => {
    form.value.nodes.splice(nodeIndex + 1, 0, {
      id: uuidv4(),
      name: '',
      commanders: [],
      isEnd: false,
      isStart: false,
      submit: false,
      fieldPermissions: template.value.componentList
        .filter((component) => component.type !== 'divider')
        .map((component) => {
          return {
            id: uuidv4(),
            fieldId: component.id,
            fieldName: component.label,
            visible: false,
            edit: false,
          }
        }),
    })
  }

  const handleNodeDelClick = (nodeIndex: number) => {
    form.value.nodes.splice(nodeIndex, 1)
  }

  onMounted(async () => {
    if (route.params.id) {
      await findTemplate(route.params.id as string)
      await findPorcessList(template.value.id)
      if (processList.value && processList.value[0]) {
        form.value = processList.value[0]
      }

      form.value.nodes = form.value.nodes.map((node) => {
        template.value.componentList
          .filter((component) => component.type !== 'divider')
          .forEach((component) => {
            const index = node.fieldPermissions.findIndex((item) => item.fieldId === component.id)
            if (index === -1) {
              const addRow = {
                id: uuidv4(),
                fieldId: component.id,
                fieldName: component.label,
                visible: false,
                edit: false,
              }
              if (!node.fieldPermissions) {
                node.fieldPermissions = [addRow]
              } else {
                node.fieldPermissions.push(addRow)
              }
            }
          })

        return node
      })
    }
  })
</script>

<template>
  <div
    v-loading="findLoading || formSaveLoading || findProcessListLoading"
    class="order-custom-process"
  >
    <div class="container">
      <div class="header">
        <div class="title">{{ template.name }}</div>
        <div class="btn-group">
          <h-button type="primary" @click="onSaveClick">保存流程</h-button>
          <h-button @click="onCancelClick">取消</h-button>
        </div>
      </div>
      <div class="divider"></div>
      <div class="main">
        <node-list
          :node-list="form.nodes"
          @node-click="handleNodeClick"
          @add-node-click="handleAddNodeClick"
          @node-del-click="handleNodeDelClick"
        />
        <template v-if="activeNode && !activeNode.isEnd">
          <div class="divider"></div>
          <setting
            ref="settingInsatnce"
            :template="template"
            :active-node="activeNode"
            @update="handleSettingUpdate"
          />
        </template>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
  :deep(.el-switch) {
    height: 22px;
  }

  .order-custom-process {
    width: 100%;
    height: calc(100vh - 92px);
    box-sizing: border-box;
    padding: 12px;

    .container {
      width: 100%;
      height: 100%;
      box-sizing: border-box;
      padding: 12px;
      background-color: #fff;
      display: flex;
      flex-direction: column;

      .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        box-sizing: border-box;
        padding: 0 8px;

        .title {
          font-size: 16px;
          font-weight: bold;
        }

        .btn-group {
          display: flex;
          column-gap: 8px;
        }
      }

      .divider {
        border-bottom: 1px dotted rgba($color: #000000, $alpha: 0.2);
        margin: 12px 0;
      }

      .main {
        width: 100%;
        flex: 1;
        display: flex;
        height: 0;

        .nodes {
          flex: 1;
          height: 100%;
          box-sizing: border-box;
          display: flex;
          flex-direction: column;
          row-gap: 4px;

          .node-header {
            display: flex;
            justify-content: flex-end;
          }
        }

        .divider {
          border-right: 1px dotted rgba($color: #000000, $alpha: 0.2);
          margin: 0 12px;
        }
      }
    }
  }
</style>
